package business_example_dao

import (
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/util/pointer"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
	"time"
)

func (cls *BusinessExample) SaveBusinessExample(ctx context.Context, businessExample *model.BusinessExample) errors.Error {
	if nil == businessExample {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDBE_LE.BE_LE.SBE_LE.150357 businessExample is nil")

		return errors.ErrorServerInternalError("IDBE_LE.BE_LE.SBE_LE.170357", "异常的传入参数")
	}

	businessExample.UpdateTime = pointer.New(time.Now().Unix())
	if nil == businessExample.CreateTime || 0 == *businessExample.CreateTime {
		businessExample.CreateTime = pointer.New(time.Now().Unix())

		if err := cls.GetDb(ctx).Model(new(model.BusinessExample)).Create(&businessExample).Error; nil != err {
			logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDBE_LE.BE_LE.SBE_LE.250357 create businessExample failed, err %v", err)

			return errors.ErrorServerInternalError("IDBE_LE.BE_LE.SBE_LE.270357", "创建数据失败")
		}

		return nil
	}

	if err := cls.GetDb(ctx).Model(new(model.BusinessExample)).Where("id = ?", businessExample.Id).Updates(&businessExample).Error; nil != err {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDBE_LE.BE_LE.SBE_LE.340357 save businessExample failed, err %v", err)

		return errors.ErrorServerInternalError("IDBE_LE.BE_LE.SBE_LE.360357", "更新数据失败")
	}

	return nil
}
